package com.example.financeapi.controller.mp;

import com.alibaba.fastjson.JSONObject;
import com.example.financeapi.config.constant.APIConstant;
import com.example.financeapi.config.wechat.mp.WxMpProperties;
import com.example.financeapi.entity.FUser;
import com.example.financeapi.service.FUserService;
import com.example.financeapi.utils.HttpUtil;
import com.example.financeapi.utils.JWTUtils;
import com.example.financeapi.utils.RedisUtils;
import com.example.financeapi.utils.XMLUtils;
import com.example.financeapi.entity.vo.ResultException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Binary Wang(https://github.com/binarywang)
 * 配置微信公众号中的接口地址：
 * http://公网可访问域名/wx/mp/portal/xxxxx
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/wx/mp/portal/{appid}")
public class WxMpPortalController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private final RedisUtils redisUtils;
    @Autowired
    private final WxMpProperties wxMpProperties;
    @Autowired
    private final FUserService fUserService;

    private final WxMpService wxService;
    private final WxMpMessageRouter messageRouter;

    /**
     * 微信公众号：接收到来自微信服务器的认证消息
     * @param appid
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable String appid,
                          @RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {

        log.info("\n微信公众号：接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature,
            timestamp, nonce, echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        if (wxService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }

        return "非法请求";
    }

    /**
     * 微信公众号：接收微信post请求
     * @param appid
     * @param requestBody
     * @param signature
     * @param timestamp
     * @param nonce
     * @param openid
     * @param encType
     * @param msgSignature
     * @return
     * @throws ResultException
     */
    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appid,
                       @RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) throws ResultException {
        log.info("\n微信公众号：接收微信post请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
            openid, signature, encType, msgSignature, timestamp, nonce, requestBody);

        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        if (!wxService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }

        /**1.解析XML*/
        org.json.JSONObject xmlJSONObj =XMLUtils.getXmlToJson(requestBody,false);
        String event = xmlJSONObj.get("Event")+"";
        if("subscribe".equals(event)){
            FUser getFUser;
            String token="";
            String getUnionID =getUnionID(openid);
            if(StringUtils.isNotBlank(getUnionID)){
                Map<String, Object> paramMap =new HashMap<>();
                paramMap.put("unionid",getUnionID);
                FUser FUser =fUserService.getFUserByCode(paramMap);
                if(FUser==null){
                    getFUser =new FUser();
                    getFUser.setUnionid(getUnionID);
                    getFUser.setMpOpenid(openid);
                    getFUser =fUserService.insert(getFUser);
                    if(getFUser!=null){
                        String id =getFUser.getId()+"";
                        if(!"0".equals(id)){
                            redisUtils.set(id,getUnionID, APIConstant.JWT_TOKEN_TIMES);
                            //生成token
                            token = JWTUtils.createJWT(id, APIConstant.JWT_TOKEN_TIMES);
                            //记录token 测试用
                            redisUtils.set(getUnionID,token, APIConstant.JWT_TOKEN_TIMES);
                            return token;
                        }
                    }
                }else{
                    String id =FUser.getId()+"";
                    if(!"0".equals(id)){
                        paramMap.put("miniappOpenid",openid);
                        FUser fUsers =fUserService.getFUserByCode(paramMap);
                        if(fUsers ==null){
                            getFUser =new FUser();
                            getFUser.setId(FUser.getId());
                            getFUser.setMpOpenid(openid);
                            fUserService.update(getFUser);
                        }
                        redisUtils.del(id);
                        redisUtils.del(getUnionID);
                        redisUtils.set(id,getUnionID, APIConstant.JWT_TOKEN_TIMES);
                        //生成token
                        token = JWTUtils.createJWT(id, APIConstant.JWT_TOKEN_TIMES);
                        //记录token 测试用
                        redisUtils.set(getUnionID,token, APIConstant.JWT_TOKEN_TIMES);
                    }
                }
            }
        }

        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(),
                timestamp, nonce, msgSignature);
            log.debug("\n消息解密后内容为：\n{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage());
        }

        log.debug("\n组装回复信息：{}", out);
        return out;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.messageRouter.route(message);
        } catch (Exception e) {
            log.error("路由消息时出现异常！", e);
        }

        return null;
    }

    /**
     * 获取微信 UnoinId
     * @param openid
     * @return
     */
    public String getUnionID(String openid){
        String unionID ="";
        String getAccessToken ="";
        try {
            String getMyAppId =wxMpProperties.getConfigs().get(0).getAppId();
            String getMyAppSecret =wxMpProperties.getConfigs().get(0).getSecret();
            getAccessToken =redisUtils.get("mp_access_token-"+getMyAppId);
            if(StringUtils.isEmpty(getAccessToken)){
                //获取token
                String getTokenApi = String.format(APIConstant.MX_ACCESS_TOKEN_URL,getMyAppId,getMyAppSecret);
                String tokenJsonStr = HttpUtil.doGetPost(getTokenApi,"GET",null);
                JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
                getAccessToken = (String) tokenJson.get("access_token");
                redisUtils.set("mp_access_token-"+getMyAppId,getAccessToken, APIConstant.TOKEN_TIMES);
            }
            //获取unionid
            String getUnionIDApi = String.format(APIConstant.GET_MP_UNIONID_URL,getAccessToken,openid);
            String JsonStr = HttpUtil.doGetPost(getUnionIDApi,"GET",null);
            JSONObject jsonObj = JSONObject.parseObject(JsonStr);
            if("1".equals(jsonObj.get("subscribe")+"")){
                unionID= (String) jsonObj.get("unionid");
            }else{
                throw new RuntimeException("获取unionid失败！该用户没有关注公众号！");
            }
        }catch (Exception e){
            throw new RuntimeException(e.getMessage(),e);
        }
        return unionID;
    }

}
